//
//  MainWindowController.m
//  sandbox
//
//  Created by 杨岑 on 12/25/14.
//  Copyright (c) 2014 杨岑. All rights reserved.
//

#import <CocoaSQLite.h>
#import "MainWindowController.h"
#import "HotspotView.h"
#import "TestWindowWC.h"
#import "TestWindow.h"
#import "TestView.h"
#import "NSString+Ext.h"
#import "MyViewControl.h"
#import "NSAlert+Ext.h"
#import "TestViewVC.h"
#import "TestMenuVC.h"
#import "MyTextDrawingView.h"
#import "NSMutableAttributedString+Ext.h"


@interface MainWindowController ()
@property (weak) IBOutlet TestWindowWC* testWindowController;
@property (weak) IBOutlet NSMenu *trayMenu;
@property (weak) IBOutlet NSViewController *openPanelAccessoryViewController;
@property (weak) IBOutlet NSMenuItem *testTrayMenu1;
@property (weak) IBOutlet NSMenuItem *testTrayMenu2;
@end

@implementation MainWindowController
{
    NSMutableDictionary* _windowControllers;
    NSStatusItem* _trayItem;
    NSViewController* _testMenuVC;
}

#pragma mark Window delegate

- (void)awakeFromNib
{
    [super awakeFromNib];

    NSLog(@"Using SQLite version %@, CocoaSQLite version %@",
          [CocoaSQLiteVersion sqliteVersion],
          [CocoaSQLiteVersion version]
          );

    const int64_t NANO  = 1000000000;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NANO), dispatch_get_main_queue(), ^{
        NSLog(@"dispatch_after job done!");
    });
    
    _windowControllers = [NSMutableDictionary dictionary];
    
    _testMenuVC = [[TestMenuVC alloc] initWithNibName:@"TestMenu" bundle:nil];
    [_testMenuVC loadView];
    [_testTrayMenu1.view setFrameSize:_testMenuVC.view.frame.size];
    _testTrayMenu1.view = _testMenuVC.view;
    
    NSButton* button = [[NSButton alloc] initWithFrame:_testMenuVC.view.frame];
    button.title = @"test";
    _testTrayMenu2.view = button;
    
    NSStatusBar* systemStatusBar = [NSStatusBar systemStatusBar];
    _trayItem = [systemStatusBar statusItemWithLength:NSVariableStatusItemLength];
    [_trayItem setMenu:_trayMenu];
    [self setTrayIcon];
    
    MyTextDrawingView* drawingView = [[MyTextDrawingView alloc] initWithFrame:NSMakeRect(0, 0, 50, 150)];
    drawingView.autoresizingMask = NSViewMinXMargin | NSViewMinYMargin | NSViewMaxXMargin | NSViewWidthSizable;
    _testTrayMenu2.view = drawingView;
    
    NSBundle* mainBundle = [NSBundle mainBundle];
    NSLog(@"%@", mainBundle.infoDictionary);
    NSString* build = [mainBundle objectForInfoDictionaryKey:(__bridge NSString*)kCFBundleVersionKey];
    NSString* version = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSLog(@"%@.%@", version, build);
    
    // Watch for system theme change (dark mode)
    [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(themeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(frameDidChange:)
                                                 name:NSViewFrameDidChangeNotification object:nil];
    NSLog(@"KVC window property: %@", [self valueForKey:@"window"]);

    NSApp.activationPolicy = NSApplicationActivationPolicyProhibited;
    self.window.isVisible = NO;
}

- (void)frameDidChange:(NSNotification*)notification
{
    //NSLog(@"frameDidChange: %@", notification);
}

- (void)themeChanged:(NSNotification*)notificaiton
{
    //[self setTrayIcon];
}

- (void)setTrayIcon
{
    static NSImage* trayIcon;
    
    if (!trayIcon)
    {
        trayIcon = [NSImage imageNamed:@"Bing-Mono"];
        [trayIcon setSize:NSMakeSize(16, 16)];
        [trayIcon setTemplate:YES];
    }
    
    if ([_trayItem respondsToSelector:@selector(button)])
    {
        _trayItem.button.image = trayIcon;
    }
    else
    {
        _trayItem.image = trayIcon;
    }
}

- (void)windowWillClose:(NSNotification *)notification
{
    //NSLog(@"windowWillClose: %@", self);
}

- (void)windowDidBecomeKey:(NSNotification *)notification
{
    //[self.window setFrame:[[NSScreen mainScreen] visibleFrame] display:YES animate:YES];
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)newFrame
{
    return [[NSScreen mainScreen] visibleFrame];
}

- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
{
    return YES;
}

- (void)windowDidResize:(NSNotification *)notification
{
    
}

#pragma mark Helper methods

- (NSWindowController*)getWindowController:(NSString*)name
{
    NSWindowController* wc = _windowControllers[name];
    
    if (!wc)
    {
        Class wcc = NSClassFromString(name);
        
        NSString* nibName = [name copy];
        if ([nibName hasSuffix:@"WC"])
        {
            nibName = [nibName substringToIndex:name.length - 2];
            @try {
                wc = [[wcc alloc] initWithWindowNibName:nibName];
            }
            @catch (NSException *exception) {
                NSLog(@"%@", exception);
            }
            @finally {
                
            }
        }
        
        _windowControllers[name] = wc;
    }
    return wc;
}

#pragma mark Event handlers

- (IBAction)testCustomView_click:(id)sender
{
    NSWindowController* wc = [self getWindowController:@"TestCustomViewWC"];
    [wc showWindow:self];
}

- (IBAction)testTextView_click:(id)sender
{
    NSWindowController* wc = [self getWindowController:@"TestTextViewWC"];
    [wc showWindow:self];
}

- (IBAction)testTransparentWindow_click:(id)sender {
    static NSWindow* w;
    
    w = [[TestWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 200) styleMask:0 backing:NSBackingStoreBuffered defer:NO];
    w.contentView = [[TestView alloc] initWithFrame:w.frame];
    [w setFrame:self.window.frame display:YES];
    [w orderFront:self];
}


- (IBAction)testOpenPanel_click:(id)sender {
    /*
    NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 200, 20)];
    NSTextField* label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 20)];
    label.stringValue = @"accessory view content";
    label.editable = NO;
    label.selectable = YES;
    label.bordered = NO;
    label.backgroundColor = [NSColor windowBackgroundColor];
    [view addSubview:label];*/
    
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    [openPanel setAllowsMultipleSelection:NO];
    [openPanel setCanChooseDirectories:YES];
    [openPanel setCanChooseFiles:NO];
    [openPanel setPrompt:@"SELECT FOLDER"];
    [openPanel setCanCreateDirectories:YES];
    [openPanel setMessage:@"Message"];
    openPanel.accessoryView = self.openPanelAccessoryViewController.view;
    
    [openPanel beginSheetModalForWindow:[self window] completionHandler:
     ^(NSInteger result) {
         if (result == NSModalResponseOK) {
             NSURL* url = [openPanel URL];
             NSLog(@"%@", url);
             //NSString* dir = [url path];
             //[[self cacheDirTextField] setStringValue:dir];
             //[self updateLocationTip];
             //[self validateSaveLocation];
         }
     }];
}

- (IBAction)testSetFrameAnimation_click:(id)sender {
    /*
    static NSWindowController* wc;
    
    if (!wc)
    {
        NSWindow* w = [[TestWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 300) styleMask:0 backing:NSBackingStoreBuffered defer:NO];
        wc = [[TestWindowController alloc] initWithWindow:w];
        [wc showWindow:self];
    }
    */
    static BOOL large = NO;
    NSWindow* w = _testWindowController.window;
    w.isVisible = YES;
    [w orderFront:self];
    NSRect frame = w.frame;
    frame.size.width += large ? -200 : 200;
    frame.size.height += large ? -300 : 300;
    [w setFrame:frame display:YES animate:YES];
    large = !large;
}

- (IBAction)testWorkspace_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestWorkspaceWC"];
    [wc showWindow:self];
}

- (IBAction)testTimer_click:(id)sender {
    static NSTimer* timer;
    
    if (!timer)
    {
        timer = [NSTimer timerWithTimeInterval:.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        //timer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    }
}

- (void)timerFired:(NSTimer *)timer
{
    NSLog(@"%@", timer);
}

- (IBAction)NSAlert_click:(id)sender
{
    NSAlert* alert = [[NSAlert alloc] init];
    alert.messageText = @"message";
    alert.informativeText = @"information text";
    //[alert addButtonWithTitle:@"test"];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    alert.showsHelp = YES;
    alert.showsSuppressionButton = YES;
    NSLog(@"NSAlert buttons: %@", alert.buttons);
    
    [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
        NSLog(@"Alert ended with %ld", returnCode);
    }];
    
    [NSAlert runModalSheet:self.window withError:[NSError errorWithDomain:@"test" code:1234 userInfo:nil]];
}

- (IBAction)testTabView_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestTabViewWC"];
    [wc showWindow:self];
}

- (IBAction)testScrollView_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestScrollViewWC"];
    [wc showWindow:self];
}

- (IBAction)testTableView_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestTableViewWC"];
    [wc showWindow:self];
}

- (IBAction)testLayoutConstraints_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestLayoutConstraintsWC"];
    [wc showWindow:self];
}

- (IBAction)testAddSubView_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestAddSubviewWC"];
    [wc showWindow:self];
}

- (IBAction)testPipeAndTask_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestPipeWC"];
    [wc showWindow:self];
}

- (IBAction)pathControl_click:(id)sender {
    NSWindowController* wc = [self getWindowController:@"TestPathControlWC"];
    [wc showWindow:self];
}

- (IBAction)trayTest1_click:(id)sender {
    NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
    self.window.isVisible = YES;
    [NSApp activate];
}

- (IBAction)trayTest2_click:(id)sender {
}

- (void)menuWillOpen:(NSMenu *)menu
{
    NSLog(@"%s: %@", __func__, menu.title);
}

- (IBAction)test_click:(id)sender
{

}

- (IBAction)dummy_click:(id)sender
{

}

@end
